//
//  GZZViewController.m
//  Estate
//
//  Created by heyong on 16/5/27.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "GZZViewController.h"
#import "SegmentViewController.h"
@interface GZZViewController ()
{
    FMDatabase *_db;
    DBHelper *_helper;
    SegmentViewController *vc ;
}
//设置按钮标题
@property (retain, nonatomic)NSArray *titArr;


@end

@implementation GZZViewController
#pragma mark-懒加载

- (NSArray *)titArr{
    if(_titArr==nil){
        _titArr=[NSArray arrayWithObjects:@"基本资料",@"人",@"机械",@"物料",@"法/环",nil];
    }
    return _titArr;
}

- (Site_05 *)site{
    if(_site==nil){
        _site=[[Site_05 alloc]init];
    }
    return _site;
}

//解决查看后 再次添加 无法显示保存按钮的bug
- (void)setFlag:(NSString *)flag{
    _flag=flag;
    if([self.flag isEqualToString:@"addty"]){
        self.edit=YES;
        self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"wancheng"] style:UIBarButtonItemStyleDone target:self action:@selector(clickSave)];
    }else if ([self.flag isEqualToString:@"look"]){
        self.edit=NO;
    }else if ([self.flag isEqualToString:@"upRecord"]){
        //判断是否超过旁站结束时间 或者 日记提取了此条记录
        //        self.edit=[LSUtility isSameDay:self.site.createTime];
        self.edit=[LSUtility siteEditForendTimeAndSiteRecordId:self.site.recordId beginTine:self.site.createTime endTime:self.site.endTime];
        if(self.edit){
            //添加右上方提交按钮
            self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"wancheng"] style:UIBarButtonItemStyleDone target:self action:@selector(clickSave)];
        }else{
            self.navigationItem.rightBarButtonItem=nil;
        }
    }
}


- (void)setSideId:(NSString *)sideId{
    _sideId=sideId;
    WEAKSELF
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *helper=[DBHelper help];
    NSDictionary *supData=[[helper DataBase:db selectKeyTypes:@{@"RECORD_NUMBER":@"text",@"RECORD_INFO":@"text",@"CREATE_TIME":@"text",@"ADDRESS_ID":@"text",@"ADDRES_INFO":@"text",@"RECORD_FILE_PATH":@"text"} fromTable:WORK_RECORD whereCondition:@{@"ID":sideId}]lastObject];
    
    NSString *dataJson=supData[@"RECORD_INFO"];
    weakSelf.site.recordId=_sideId;
    //得到附件数组
    NSString *fileJson=DEFISNUL(supData[@"RECORD_FILE_PATH"]);
    weakSelf.site.fileArray=[LSUtility dictionaryWithJsonString:fileJson];
    
    NSDictionary *siteDic=[LSUtility dictionaryWithJsonString:dataJson];
    weakSelf.site.createTime=supData[@"CREATE_TIME"];
    //位置
    weakSelf.site.locationInfo=DEFISNUL(siteDic[@"locationInfo"]);
    weakSelf.site.locationId=DEFISNUL(supData[@"ADDRESS_ID"]);
    weakSelf.site.location=DEFISNUL(supData[@"ADDRES_INFO"]);
    
    NSDictionary *RDic=siteDic[@"人"];
    weakSelf.site.zaigangNum=RDic[gzz_r_zaig];
    weakSelf.site.gongbanNum=RDic[gzz_r_gongb];
    weakSelf.site.guanliNum=RDic[gzz_r_guanl];
    weakSelf.site.zuanJiNum=RDic[gzz_r_zuanj];
    weakSelf.site.gangjNum=RDic[gzz_r_gangj];
    weakSelf.site.qitname=RDic[gzz_r_qit];
    weakSelf.site.qitnum=RDic[gzz_r_qitnum];
    weakSelf.site.fuzNum=RDic[gzz_r_fuz];
    weakSelf.site.isR=RDic[hnt_r_8];
    
    //法环
    NSDictionary *FHDic=siteDic[@"法环"];
    weakSelf.site.is_fh_1=FHDic[gzz_fh_is1];
    weakSelf.site.is_fh_2=FHDic[gzz_fh_is2];
    weakSelf.site.is_fh_3=FHDic[gzz_fh_is3];
    weakSelf.site.is_fh_4=FHDic[gzz_fh_is4];
    weakSelf.site.fh_1=FHDic[gzz_fh_1];
    weakSelf.site.fh_2=FHDic[gzz_fh_2];
    weakSelf.site.text=FHDic[@"发现的问题及处理情况"];
    weakSelf.site.fh_hnt=FHDic[@"终孔前及浇筑检查情况"];
    
    //机械
    NSDictionary *JXDic=siteDic[@"机械"];
    weakSelf.site.jixie1_num=JXDic[gzz_jx_xuanw];
    weakSelf.site.jixie2_num=JXDic[gzz_jx_changl];
    weakSelf.site.jixie3_num=JXDic[gzz_jx_mopan];
    weakSelf.site.jixie4_num=JXDic[gzz_jx_qtck];
    weakSelf.site.jixie5_num=JXDic[gzz_jx_qic];
    weakSelf.site.jixie6_num=JXDic[gzz_jx_dib];
    weakSelf.site.jixie7_num=JXDic[gzz_jx_zhij];
    weakSelf.site.jixie8_num=JXDic[gzz_jx_waj];
    weakSelf.site.jixie9_num=JXDic[gzz_jx_qtjx];
    weakSelf.site.isJ=JXDic[gzz_jx_1];
    weakSelf.site.isJ_1=JXDic[gzz_jx_2];
    
    //物料
    NSDictionary *WLDic=siteDic[@"物料"];
    weakSelf.site.wl_1=WLDic[gzz_wl_1];
    weakSelf.site.wl_2=WLDic[gzz_wl_2];
    weakSelf.site.wl_3=WLDic[gzz_wl_3];
    
    //基本信息
    NSDictionary *XXDic=siteDic[@"基本信息"];
    weakSelf.site.beginTime=XXDic[@"开始时间"];
    weakSelf.site.endTime=XXDic[@"结束时间"];
    weakSelf.site.weather=XXDic[@"天气"];
    weakSelf.site.danwei=XXDic[@"施工单位"];
    weakSelf.site.jlName=XXDic[@"旁站监理人"];
    weakSelf.site.diqu=XXDic[@"地区"];
    weakSelf.site.number=supData[@"RECORD_NUMBER"];
    
    //工序
    NSDictionary *XXDic_1=XXDic[@"工序"];
    weakSelf.site.otherAddress=XXDic_1[@"关键工序"];
    weakSelf.site.duan=XXDic_1[@"段"];
    weakSelf.site.ceng=XXDic_1[@"层"];
    weakSelf.site.lou=XXDic_1[@"楼"];
    

    
}

- (void)viewWillAppear:(BOOL)animated{
    //根据flag 选择性刷新页面
    if(self.isSubStr!=nil){
        [self createsliderBtn];
    }
}

- (void)viewDidDisappear:(BOOL)animated{
    //清除flag：确保进入二级页面后 返回数据不会清空
    self.isSubStr=nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"旁站-混凝土灌注桩-记录";
    self.view.backgroundColor=[UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1.00];
    _helper=[DBHelper help];
    _db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];

    
}
//!!!!:保存视图
- (void)clickSave{
    //施工单位必填
    if([self.gzzzlCtr.dataDic[@"施工单位"] isEqual:@""]){
        [LSUtility showToastWithMessage:@"请选择施工单位" inView:self.view Andtime:1.];
    }
    else if(self.gzzzlCtr.locationDic[@"locationInfo"]==nil)
    {
        [LSUtility showToastWithMessage:@"位置信息不能为空" inView:self.view Andtime:1.];
    }
    
    else
    {
        if([self.flag isEqualToString:@"addty"]){
            [self addDataBase];
        }else if ([self.flag isEqualToString:@"upRecord"]){
            [self upDataBase];
        }else{
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

#pragma mark - 新增数据
- (void)addDataBase{
    WEAKSELF
    /*
     *  位置表新增数据
     */
    NSString *recordId=[NSUUID UUID].UUIDString;
    
    NSMutableArray *fileArr= [self insertAttachment:recordId];
    
    NSString *recordInFoPath=[LSUtility dictionaryToJson_2:fileArr];
    
    /*
     *  工作记录表新增数据
     **/
    //数据结构法，存入数据库
    NSDictionary *dataDic=@{@"人":weakSelf.gzzrCtr.dataDic,@"法环":weakSelf.gzzfhCtr.dataDic,@"基本信息":weakSelf.gzzzlCtr.dataDic,@"物料":weakSelf.gzzwlCtr.dataDic,@"机械":weakSelf.gzzjxCtr.dataDic,@"locationInfo":weakSelf.gzzzlCtr.locationDic[@"locationInfo"]};
    //字典转json   RECORD_INFO
    NSString *strData=[LSUtility dictionaryToJson:dataDic];
//    NSLog(@"新增:%@",strData);
    NSString *role=DEF_PERSISTENT_GET_OBJECT(@"role");
    if([role isEqualToString:@"USER_01"]){
        role=@"0";
    }else if ([role isEqualToString:@"USER_03"]||[role isEqualToString:@"USER_07"]){
        role=@"1";
    }
    //标题
    NSDictionary* dic= weakSelf.gzzzlCtr.dataDic[@"工序"];
    NSString *louStr=dic[@"楼"];
    NSString *cStr=dic[@"层"];
    NSString *dStr=dic[@"段"];
    NSString *gjStr=dic[@"关键工序"];
    
    NSString *titleStr=[NSString stringWithFormat:@"%@楼%@层%@段%@工序",louStr,cStr,dStr,gjStr];

    NSString *diqu=[weakSelf.gzzzlCtr.dataDic objectForKey:@"地区"];
    NSString *weather=[weakSelf.gzzzlCtr.dataDic objectForKey:@"天气"];
    NSString *wea=[NSString stringWithFormat:@"%@/%@",diqu,weather];
    //字段及对应值
    NSDictionary *pragameDic=[NSDictionary dictionary];
    //得到开始时间 存入创建时间
    NSString *createTime=weakSelf.gzzzlCtr.dataDic[@"开始时间"];

    pragameDic=@{
                 @"ID":recordId,
                 @"PRO_ID":DEF_PERSISTENT_GET_OBJECT(@"proid"),
                 @"RECORD_USER":DEF_PERSISTENT_GET_OBJECT(@"userid"),
                 @"RECORD_MASTER":@"",
                 @"RECORD_SUPERVISION_USER":@"",
                 @"WEATHER":wea,
                 @"ADDRESS_ID":weakSelf.gzzzlCtr.locationDic[@"locationId"],
                 @"ADDRES_INFO":weakSelf.gzzzlCtr.locationDic[@"location"],
                 @"RECORD_TYPE":@"RECORD_02_05",
                 @"RECORD_TITLE":@"混凝土灌注桩施工旁站",
                 @"RECORDONTENT":@"",
                 @"RECORD_FILE_PATH":recordInFoPath,
                 @"RECORD_INFO":strData,
                 @"STATE":role,
                 @"RECORD_NUMBER":@"",
                 @"EXTEND_INFO":titleStr,
                 @"CREATE_USER_NAME":@"anonymous",
                 @"CREATE_TIME":createTime,
                 @"CREATE_IP":[LSUtility getIPAddress],
                 @"LOCAL_MODIFY_STATE":@"ADD",
                 };
        BOOL isAdd=[_helper DataBase:_db insertKeyValues:pragameDic intoTable:WORK_RECORD];
        if(isAdd){
            NSLog(@"旁站-通用新增成功");
            NSNotification * notice = [NSNotification notificationWithName:@"Refresh_jl_pz" object:nil userInfo:nil];
            [[NSNotificationCenter defaultCenter]postNotification:notice];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            NSLog(@"旁站-通用新增失败");
        }
}

//附件存入
-(NSMutableArray *)insertAttachment:(NSString *)recordIds{
    WEAKSELF
    NSMutableArray *recordFileArr=[NSMutableArray array];;
    //人附件存入附件表
    weakSelf.gzzrCtr.selectedAssetURLs = [weakSelf.gzzrCtr.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
    
    if(weakSelf.gzzrCtr.selectedAssetURLs.count>0){
        NSMutableArray *rFileArr=[LSUtility insertAttachmentSiteFromArray:weakSelf.gzzrCtr.selectedAssetURLs andRecordId:recordIds andType:@"RECORD_02_05" andChildType:@"RECORD_02_SIDE_01"];
        for (NSDictionary *dic in rFileArr) {
            [recordFileArr addObject:dic];
        }
    }
    
    //机械附件存入
    weakSelf.gzzjxCtr.selectedAssetURLs = [weakSelf.gzzjxCtr.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
    
    if(weakSelf.gzzjxCtr.selectedAssetURLs.count>0){
        NSMutableArray *JXFileArr=[LSUtility insertAttachmentSiteFromArray:weakSelf.gzzjxCtr.selectedAssetURLs andRecordId:recordIds andType:@"RECORD_02_05" andChildType:@"RECORD_02_SIDE_02"];
        for (NSDictionary *dic in JXFileArr) {
            [recordFileArr addObject:dic];
        }
    }
    
    //物料附件存入
    weakSelf.gzzwlCtr.selectedAssetURLs = [weakSelf.gzzwlCtr.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
    
    if(weakSelf.gzzwlCtr.selectedAssetURLs.count>0){
        NSMutableArray *wlFileArr=[LSUtility insertAttachmentSiteFromArray:weakSelf.gzzwlCtr.selectedAssetURLs andRecordId:recordIds andType:@"RECORD_02_05" andChildType:@"RECORD_02_SIDE_03"];
        for (NSDictionary *dic in wlFileArr) {
            [recordFileArr addObject:dic];
        }
    }
    //法环附件存入
    weakSelf.gzzfhCtr.selectedAssetURLs = [weakSelf.gzzfhCtr.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
    
    if(weakSelf.gzzfhCtr.selectedAssetURLs.count>0){
        NSMutableArray *fhFileArr=[LSUtility insertAttachmentSiteFromArray:weakSelf.gzzfhCtr.selectedAssetURLs andRecordId:recordIds andType:@"RECORD_02_05" andChildType:@"RECORD_02_SIDE_04"];
        for (NSDictionary *dic in fhFileArr) {
            [recordFileArr addObject:dic];
        }
    }
    return recordFileArr;
}

#pragma mark - 修改数据
- (void)upDataBase{
    WEAKSELF
    if(self.edit){
        NSMutableArray *fileArr= [self insertAttachment:_sideId];
        
        NSString *recordInFoPath=[LSUtility dictionaryToJson_2:fileArr];
        //数据结构法，存入数据库
        NSDictionary *dataDic=@{@"人":weakSelf.gzzrCtr.dataDic,
                                @"法环":weakSelf.gzzfhCtr.dataDic,
                                @"基本信息":weakSelf.gzzzlCtr.dataDic,
                                @"ADDRESS_ID":weakSelf.gzzzlCtr.locationDic[@"locationId"],
                                @"ADDRES_INFO":weakSelf.gzzzlCtr.locationDic[@"location"],
                                @"机械":weakSelf.gzzjxCtr.dataDic,
                                @"物料":weakSelf.gzzwlCtr.dataDic,
                        @"locationInfo":weakSelf.gzzzlCtr.locationDic[@"locationInfo"]};
        //字典转json   RECORD_INFO
        NSString *strData=[LSUtility dictionaryToJson:dataDic];
        NSLog(@"修改物料:%@",[LSUtility dictionaryToJson_2:weakSelf.gzzwlCtr.dataDic]);
        ///标题，楼层段工序
        NSDictionary* dic= weakSelf.gzzzlCtr.dataDic[@"工序"];
        NSString *louStr=dic[@"楼"];
        NSString *cStr=dic[@"层"];
        NSString *dStr=dic[@"段"];
        NSString *gjStr=dic[@"关键工序"];
        
        NSString *titleStr=[NSString stringWithFormat:@"%@楼%@层%@段%@工序",louStr,cStr,dStr,gjStr];
        
        NSString *diqu=[weakSelf.gzzzlCtr.dataDic objectForKey:@"地区"];
        NSString *weather=[weakSelf.gzzzlCtr.dataDic objectForKey:@"天气"];
        NSString *wea=[NSString stringWithFormat:@"%@/%@",diqu,weather];
        
        //字段及对应值
        NSDictionary *pragameDic=[NSDictionary dictionary];
        pragameDic=@{
                     @"RECORD_INFO":strData,
                     @"WEATHER":wea,
                     @"EXTEND_INFO":titleStr,
                     @"MODIFY_TIME":[LSUtility nowTime],
                     @"RECORD_FILE_PATH":recordInFoPath,
                     @"LOCAL_MODIFY_STATE":@"MOD",
                     };
        
        [_helper DataBase:_db updateTable:WORK_RECORD setKeyValues:pragameDic whereCondition:@{@"ID":_sideId}];
        NSNotification * notice = [NSNotification notificationWithName:@"Refresh_jl_pz" object:nil userInfo:nil];
        [[NSNotificationCenter defaultCenter]postNotification:notice];
        
    }
    [self.navigationController popViewControllerAnimated:YES];
}

//!!!:创建滑动视图
- (void)createsliderBtn{
    WEAKSELF
    
    if(vc){
        [vc.view removeFromSuperview];
    }
    vc = [[SegmentViewController alloc]init];
    vc.height = DEF_SCREEN_HEIGHT - 108;
    vc.titleArray = self.titArr;
    _gzzrCtr=[[GZZRViewController alloc]init];
    _gzzzlCtr=[[GZZZLViewController alloc]init];
    _gzzfhCtr=[[GGZFHViewController alloc]init];
    _gzzjxCtr=[[GZZJXViewController alloc]init];
    _gzzwlCtr=[[GZZWLViewController alloc]init];
    
    //查看页面
    if(![self.flag isEqualToString:@"addty"]){
        //查看详情 设置数据model
        weakSelf.gzzzlCtr.site=weakSelf.site;
        weakSelf.gzzrCtr.site=weakSelf.site;
        weakSelf.gzzjxCtr.site=weakSelf.site;
        weakSelf.gzzwlCtr.site=weakSelf.site;
        weakSelf.gzzfhCtr.site=weakSelf.site;
        
        //时间是当天，允许编辑
        weakSelf.gzzzlCtr.isEdit=self.edit;
        weakSelf.gzzrCtr.isEdit=self.edit;
        weakSelf.gzzjxCtr.isEdit=self.edit;
        weakSelf.gzzwlCtr.isEdit=self.edit;
        weakSelf.gzzfhCtr.isEdit=self.edit;
        
    }else{
        //添加页面 允许编辑
        weakSelf.gzzzlCtr.isEdit=YES;
        weakSelf.gzzrCtr.isEdit=YES;
        weakSelf.gzzjxCtr.isEdit=YES;
        weakSelf.gzzwlCtr.isEdit=YES;
        weakSelf.gzzfhCtr.isEdit=YES;
    }
    
    NSMutableArray *controlArray = [[NSMutableArray alloc]initWithObjects:self.gzzzlCtr,self.gzzrCtr,self.gzzjxCtr,self.gzzwlCtr,self.gzzfhCtr ,nil];
    //设置选中字体颜色
    vc.titleSelectedColor = [TTTheme defaultManger].defaultColor;
    //设置子视图
    vc.subViewControllers = controlArray;
    //标签栏背景色
    vc.headViewBackgroundColor=[UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1.00];
    //非选中状态下标签字体大小
    vc.fontSize=14.;
    //选中下划线颜色
    vc.bottomLineColor=[TTTheme defaultManger].defaultColor;
    
    vc.buttonWidth = DEF_SCREEN_WIDTH/5;
    vc.buttonHeight = 40;
    [vc initSegment];
    [vc addParentController:self];
}


@end
